enum Status {
  FAIL = 'fail',
  ERROR = 'error',
  SUCCESS = 'success',
}

export enum Code {
  ADD_SUCCESS = 200001,
  DELETE_SUCCESS = 200002,
  UPDATE_SUCCESS = 200003,
  SELECT_SUCCESS = 200004,

  UNKNOWN_ERROR = 500000,
  ADD_ERROR = 500001,
  DELETE_ERROR = 500002,
  UPDATE_ERROR = 500003,
  SELECT_ERROR = 500004,

  ARGUMENTS_ERROR = 400001,
}

function getMessage(code: Code) {
  switch (code) {
    case Code.ADD_SUCCESS:
      return '添加成功';
    case Code.DELETE_SUCCESS:
      return '删除成功';
    case Code.UPDATE_SUCCESS:
      return '更新成功';
    case Code.SELECT_SUCCESS:
      return '查询成功';

    case Code.UNKNOWN_ERROR:
      return '服务器错误';
    case Code.ADD_ERROR:
      return '添加失败';
    case Code.DELETE_ERROR:
      return '删除失败';
    case Code.UPDATE_ERROR:
      return '更新失败';
    case Code.SELECT_ERROR:
      return '查询失败';

    case Code.ARGUMENTS_ERROR:
      return '参数校验错误';
  }
}

class Result {
  constructor(
    public readonly status: Status,
    public readonly code: Code,
    public readonly message: string,
    public readonly data: any,
    public readonly error: any,
  ) {}

  toJson() {
    return JSON.stringify({
      status: this.status,
      code: this.code,
      message: this.message,
      data: this.data,
      error: this.error,
    });
  }
}

// 操作成功
export function success(code: Code, data: any) {
  return new Result(Status.SUCCESS, code, getMessage(code), data, {});
}

// 服务器错误 如业务逻辑出错
export function fail(code: Code) {
  return new Result(Status.FAIL, code, getMessage(code), {}, {});
}

// 客户端错误 如参数格式有误
export function error(code: Code, error: any) {
  return new Result(Status.ERROR, code, getMessage(code), {}, error);
}
